<script setup>
  import { ref, onMounted, inject, defineExpose, nextTick } from 'vue'
  import {
    Promotion, FolderOpened
  } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { getSignature } from '/@/utils';
  // import {
  //   uploadFileOss
  // } from '@/api/createAquote/index.js'
  import { Local, Session } from '/@/utils/storage';

  const goEasy = inject('goeasy')
  const pubsub = goEasy.pubsub;
  const historyMessage = ref([])
  const text = ref('')
  const userInfo = JSON.parse(Local.get('userInfo'));// 用户信息

  const id = userInfo.id  // 个人ID  后续替换
  const data = { name: userInfo.username }  // 个人信息
  const receiverId = ref('') // 发送人ID


  const initGoEasy = async () => {
    await nextTick();
    loadHistoryMessage();
  }

  // 链接goEasy
  const connectGoEasy = () => {
    goEasy.connect({
      id, // 用户id
      data, // 用户信息
      onSuccess: function () {  //连接成功
        console.log("连接成功")
        goEasy.im.on('message', (message) => {
          console.log('收到实时消息:', message);
        });
        // goEasy.im.on(goEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onReceivedPrivateMessage);
        // goEasy.im.on(goEasy.IM_EVENT.CONVERSATIONS_UPDATED, renderConversations); // 消息列表
      },
      onFailed: function (error) { //连接失败
        console.log("连接失败,code:" + error.code + ",error:" + error.content);
      },
      onProgress: function (attempts) { //连接或自动重连中
        console.log("GoEasy is connecting", attempts);
      }
    });
  }

  // 发送消息
  const sendMessage = (message) => {
    // 添加标志位防止重复发送
    if (message._isSending) return;
    message._isSending = true;
    goEasy.im.sendMessage({
      message: message,
      onSuccess: () => {
        ossFileList.value = [];
        loadHistoryMessage();
        console.log('发送成功');
        // 发送成功后重置标志位
        delete message._isSending;
      },
      onFailed: (error) => {
        console.log('发送失败:', error);
        delete message._isSending; // 失败时也重置
      }
    });
  }

  // 输入框 键盘事件
  const handleInputKeydown = (e) => {
    if (e.key === 'Enter') {
      if (e.shiftKey) {
        return;
      } else {
        e.preventDefault();
        sendTextMessage();
      }
    }
  }

  // 创建消息
  const sendTextMessage = () => {
    const toData = {
      id: String(receiverId.value),
      type: 'private',
      data: {
        name: "Tracy"
      },
    }
    const payload = {
      orderId: '20250728063829542',
      text: text.value,
      image: ossFileList.value,
    }
    console.log(toData);
    
    goEasy.im.createCustomMessage({
      to: toData,
      type: ossFileList.value.length > 0 ? 'fileImage' : 'oneselfText',
      payload: payload,
      onSuccess: (message) => {
        sendMessage(message);
      },
      onFailed: (err) => {
        console.log("创建消息err:", err);
      }
    });
  }

  // 获取消息 / 历史记录
  const loadHistoryMessage = () => {
    goEasy.im.history({
      id: String(receiverId.value),
      type: 'private',
      lastTimestamp: null,
      limit: 20, // 适当增加加载数量，减少频繁请求
      onSuccess: (result) => {
        text.value = '';
        console.log(result);

        historyMessage.value = result.content;
        markPrivateMessageAsRead();
      },
      onFailed: (error) => {
        console.log('获取历史消息失败:', error);
      },
    });
  }

  // 已读消息
  const markPrivateMessageAsRead = () => {
    goEasy.im.markMessageAsRead({
      id: String(receiverId.value),
      type: 'private',
      onSuccess: function () {
        console.log('标记私聊已读成功');
      },
      onFailed: function (error) {
        console.log('标记私聊已读失败', error);
      },
    });
  }

  // 发送自定义订单信息
  const orderInfo = { orderId: '20250728063829542', orderName: '订单名称' };
  const sendOrderMessage = () => {
    const toData = {
      id: String(receiverId.value),
      type: "private",
      data: {
        name: "Tracy"
      }
    }
    const payload = {
      orderId: '20250728063829542',
      text: text.value,
    }
    goEasy.im.createCustomMessage({
      to: toData,
      type: 'orderInfo',
      payload: payload,
      onSuccess: (message) => {
        console.log("创建消息:", message);
        sendMessage(message);
      },
      onFailed: (err) => {
        console.log("创建消息err:", err);
      }
    });
  }

  // 文件上传处理
  const ossFileList = ref([]);
  const handleFileUpload = async (file) => {
    const formData = new FormData();
    formData.append('file', file.file, file.name)
    formData.append('signature', getSignature({}))


    const token = Session.get('token')
    const url = import.meta.env.VITE_API_URL + '/admin/upload/oss'
    axios
      .post(url, formData, {
        headers: {
          'x-access-token': token || '',
          'X-Access-Appid': 'admin',
          'Authorization': token || '',
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((response) => {
        const ossFilePath = response.data.data[0].oss_upload_files_path
        console.log(ossFilePath);
        
        ossFileList.value.push(ossFilePath);

      })
      .catch((error) => {
        console.log('Upload error:', error)
      })
  };

  // 添加文件删除方法
  const clickDelFile = (index) => {
    ossFileList.value.splice(index, 1); // 删除指定索引的文件路径
    ElMessage.success('文件删除成功');
  };

  defineExpose({
    receiverId,
    initGoEasy,
    sendOrderMessage,
    loadHistoryMessage,
  });
</script>

<template>
  <div class="goeasy-content">
    <div class="history-content">
      <div v-for="(item, index) in historyMessage" :key="index">
        <!-- 消息容器 -->
        <div class="history-item" v-if="item.type == 'oneselfText' || item.type == 'fileImage'">

          <div :class="['file-message',{ 'file-receiver': item.senderId == id}]" v-if="item.payload.image.length > 0">
            <img v-for="(item, index) in item.payload.image" :key="index" :src="item" />
          </div>
          <div v-if="item.payload.text" :class="['message-box', { 'message-receiver': item.senderId == id}]">
            <!-- <span>{{item.senderId == id ? '我' : '对方'}}</span> -->
            <div class="message-content">{{ item.payload.text }}</div>
            <!-- {{item.read ? '已读' : '未读'}} -->
          </div>
        </div>
        <!-- 订单容器 -->
        <div class="history-order" v-if="item.type == 'orderInfo'">
          订单id: {{item.payload.orderId}}
        </div>
      </div>
    </div>
    <div class="file-list">
      <div class="image-box" v-for="(item, index) in ossFileList" :key="index">
        <img :src="item" class="file-image">
        <el-icon class="del-icon" @click="clickDelFile(index)">
          <ele-CircleCloseFilled />
        </el-icon>
      </div>
    </div>
    <div class="input-box">
      <el-input v-model="text" @keydown="handleInputKeydown" class="input-content" :rows="3" type="textarea"
        placeholder="请输入" />
      <el-upload action="#" :show-file-list="false" :http-request="handleFileUpload" class="button-content"
        style="right: 40px;" accept="image/*">
        <el-button type="primary" :icon="FolderOpened" circle />
      </el-upload>
      <el-button type="primary" class="button-content" @click="sendTextMessage" :icon="Promotion" circle />
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .file-message {
    display: flex;
    margin-bottom: 12px;

    &.file-receiver {
      justify-content: flex-end;
    }

    img {
      width: 120px;
      height: 120px;
      margin-right: 12px;
    }
  }

  .file-list {
    margin-bottom: 12px;

    .image-box {
      width: 60px;
      height: 60px;
      position: relative;

      .del-icon {
        width: 20px;
        height: 20px;
        position: absolute;
        top: -10px;
        font-size: 18px;
        right: -10px;
        color: #f00;
      }

      .file-image {
        width: 60px;
        height: 60px;
        margin-right: 12px;
      }
    }
  }

  .history-content {
    width: 100%;
    height: 65vh;
    overflow-y: auto;

    .history-item {
      margin-bottom: 12px;

      .message-box {
        display: flex;
        align-items: center;

        .message-content {
          margin: 0 12px;
          padding: 3px 8px;
          border-radius: 4px;
          text-align: left;
          background-color: #e5e7eb;
        }
      }

      .message-receiver {
        flex-direction: row-reverse;

        .message-content {
          color: #fff;
          background-color: rgb(74 137 220 / var(--tw-bg-opacity, 1));
        }
      }
    }
  }

  .input-box {
    position: relative;

    .button-content {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }

  .history-order {
    color: #666;
    text-align: center;
    position: relative;
    margin-bottom: 20px;
  }
</style>